import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
import { LoadingBarVnode } from './components/LoadingBar/loadingBar'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import {createPinia} from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import 'element-plus/theme-chalk/dark/css-vars.css'
// import './styles/dark/css-vars.css'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

// TODO 如何解决页面大规模请求并发？尝试使用防抖，节流，请求队列，合并请求等方式来应对

const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

app.use(router)
app.use(pinia)

const userWhiteList: Array<string|RegExp> = [
    '/',
    '/register',
    '/home',
    '/home/personalInfo',
    '/home/personalInfo/info',
    '/home/personalInfo/password',
    '/home/personalInfo/history',
    '/home/personalInfo/setting',
    '/home/personalInfo/collection',
    '/home/identification',
    '/home/birdAtlas',
    /^\/home\/birdDetail\/.*/
]
const adminWhiteList: Array<string|RegExp> = [
    '/',
    '/register',
    '/admin',
    '/admin/userMgt',
    '/admin/birdMgt',
    '/admin/historyMgt',
    '/admin/collectionMgt',
    '/admin/dataCollect',
    '/admin/dataProcess',
    '/admin/log',
    '/admin/identificationAdmin',
    '/admin/uploadModel'
]

//   路由拦截
router.beforeEach((to, from, next) => {
    LoadingBarVnode.component?.exposed?.startLoading()
    const token = localStorage.getItem('token')
    const userStore = useUserStore()
    const userType = userStore.user.userType
    if (['/', '/register'].includes(to.path)) {
        next()
        return
    }
    if (!token) {
        next('/')
        return
    }
    // 判断权限
    if (userType === 'admin') {
        // 管理员只能访问adminWhiteList
        const canAccess = adminWhiteList.some(item => {
            if (Object.prototype.toString.call(item) === '[object RegExp]') return (item as RegExp).test(to.path)
            return item === to.path
        })
        if (canAccess) {
            next()
        } else {
            ElMessage.warning('您没有权限访问该页面，已为您跳转到管理员首页')
            next('/admin')
        }
    } else {
        // 普通用户只能访问userWhiteList
        const canAccess = userWhiteList.some(item => {
            if (Object.prototype.toString.call(item) === '[object RegExp]') return (item as RegExp).test(to.path)
            return item === to.path
        })
        if (canAccess) {
            next()
        } else {
            ElMessage.warning('您没有权限访问该页面，已为您跳转到用户首页')
            next('/home')
        }
    }
})

router.afterEach((to, from) => {
    LoadingBarVnode.component?.exposed?.endLoading()
})

app.mount('#app')
